using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using StudentManagement.Application.DTOs;
using StudentManagement.Application.Services;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace StudentManagement.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        private readonly IStudentService _studentService;

        public StudentController(IStudentService studentService)
        {
            _studentService = studentService;
        }

        // GET: api/Student
        [HttpGet]
        [Authorize]
        public async Task<ActionResult<IEnumerable<StudentDTO>>> GetAllStudents()
        {
            var students = await _studentService.GetAllStudentsAsync();
            return Ok(students);
        }

        // GET: api/Student/{id}
        [HttpGet("{id}")]
        [Authorize]
        public async Task<ActionResult<StudentDTO>> GetStudentById(int id)
        {
            var student = await _studentService.GetStudentByIdAsync(id);
            if (student == null)
            {
                return NotFound();
            }
            return Ok(student);
        }

        // GET: api/Student/by-student-id/{studentId}
        [HttpGet("by-student-id/{studentId}")]
        [Authorize]
        public async Task<ActionResult<StudentDTO>> GetStudentByStudentId(string studentId)
        {
            var student = await _studentService.GetStudentByStudentIdAsync(studentId);
            if (student == null)
            {
                return NotFound();
            }
            return Ok(student);
        }

        // GET: api/Student/by-class/{classId}
        [HttpGet("by-class/{classId}")]
        [Authorize]
        public async Task<ActionResult<IEnumerable<StudentDTO>>> GetStudentsByClassId(int classId)
        {
            var students = await _studentService.GetStudentsByClassIdAsync(classId);
            return Ok(students);
        }

        // GET: api/Student/search/{keyword}
        [HttpGet("search/{keyword}")]
        [Authorize]
        public async Task<ActionResult<IEnumerable<StudentDTO>>> SearchStudents(string keyword)
        {
            var students = await _studentService.SearchStudentsAsync(keyword);
            return Ok(students);
        }

        // POST: api/Student
        [HttpPost]
        [Authorize(Roles = "Admin,Teacher")]
        public async Task<ActionResult<StudentDTO>> CreateStudent([FromBody] StudentDTO studentDTO)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                var createdStudent = await _studentService.CreateStudentAsync(studentDTO);
                return CreatedAtAction(nameof(GetStudentById), new { id = createdStudent.Id }, createdStudent);
            }
            catch (System.Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // PUT: api/Student/{id}
        [HttpPut("{id}")]
        [Authorize(Roles = "Admin,Teacher")]
        public async Task<ActionResult<StudentDTO>> UpdateStudent(int id, [FromBody] StudentDTO studentDTO)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                var updatedStudent = await _studentService.UpdateStudentAsync(id, studentDTO);
                if (updatedStudent == null)
                {
                    return NotFound();
                }
                return Ok(updatedStudent);
            }
            catch (System.Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // DELETE: api/Student/{id}
        [HttpDelete("{id}")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> DeleteStudent(int id)
        {
            try
            {
                await _studentService.DeleteStudentAsync(id);
                return Ok(new { success = true });
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("学生不存在"))
                {
                    return NotFound(new { message = ex.Message });
                }
                return BadRequest(new { message = ex.Message });
            }
        }

        // GET: api/Student/student-id-exists/{studentId}
        [HttpGet("student-id-exists/{studentId}")]
        [Authorize(Roles = "Admin,Teacher")]
        public async Task<ActionResult<bool>> StudentIdExists(string studentId)
        {
            var exists = await _studentService.StudentIdExistsAsync(studentId);
            return Ok(exists);
        }
    }
}